package com.example.echoewish.ui.main_activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.echoewish.ui.my_activity.chat_activity.ChatActivity;
import com.example.echoewish.ui.my_activity.friend_request_activity.FriendRequestActivity;
import com.example.echoewish.ui.my_activity.login_and_register_activity.LoginAndRegisterActivity;
import com.example.echoewish.ui.my_activity.my_comment_activity.MyCommentActivity;
import com.example.echoewish.ui.my_activity.my_friend_activity.MyConcernActivity;
import com.example.echoewish.ui.my_activity.my_publish_activity.MyPublishActivity;
import com.example.echoewish.ui.my_activity.other_comment_activity.OthersCommentActivity;
import com.example.echoewish.R;
import com.example.echoewish.ui.my_activity.user_info_activity.UserInfoShowActivity;
import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyFragment extends Fragment {
    private static int CHANGE_HEAD_SUCCESSFUL=3;
    private static  int CHANGE_HEAD_FAIL=4;

    private TextView nameTextView;
    private CircleImageView headImageView;
    private Button my_publish_button;
    private Button my_comment_button;
    private LinearLayout myMessageLinearLayout;
    private LinearLayout myConcernLinearLayout;
    private LinearLayout myHomePageLinearLayout;
    private LinearLayout myPrivateMessageLinearLayout;

    private File outputImage=null;
    private Uri imageUri;

    private MyViewModel myViewModel;


    private Handler MyHandler=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE:
                    if(msg.arg1==CHANGE_HEAD_SUCCESSFUL)
                    {
                        if(getActivity()!=null)
                        {
                            Toast.makeText(getActivity(),"上传头像成功",Toast.LENGTH_SHORT).show();
                            Glide.with(MyFragment.this.getActivity()).load(outputImage).into(headImageView);
                        }
                    }
                    else if(msg.arg1==CHANGE_HEAD_FAIL)
                    {
                        if(getActivity()!=null)
                            Toast.makeText(getActivity(),"上传头像失败",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case Constant.HTTPS_GET_CALLBACK_FAIL_MESSAGE:
                    if(getActivity()!=null)
                    Toast.makeText(getActivity(),"无网络连接",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public MyFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_my, container, false);
        nameTextView =view.findViewById(R.id.name_text_view);
        headImageView=view.findViewById(R.id.head_image_view);
        myHomePageLinearLayout=view.findViewById(R.id.my_private_homepage_layout);
        myMessageLinearLayout=view.findViewById(R.id.my_message_line_layout);
        myConcernLinearLayout=view.findViewById(R.id.my_concern_linelayout);
        myPrivateMessageLinearLayout=view.findViewById(R.id.my_private_message_layout);

        //设置布局
        my_publish_button=view.findViewById(R.id.my_publish_button);


        my_comment_button=view.findViewById(R.id.my_comment_button);


        //根据是否登录 决定是否赋值
        if(UserInfo.getInstance().IsLogin)
        {
            nameTextView.setText(UserInfo.getInstance().name);
            if(UserInfo.getInstance().headImage!=null&&!UserInfo.getInstance().headImage.equals(""))
                Glide.with(getActivity()).load(Constant.HEAD_IMAGE_URL+UserInfo.getInstance().headImage).into(headImageView);
            else
                Glide.with(getActivity()).load(R.drawable.no_load).into(headImageView);
        }

        //设置监听器
        nameTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!UserInfo.getInstance().IsLogin)
                {
                    Intent intent =new Intent(getActivity(), LoginAndRegisterActivity.class);
                    startActivityForResult(intent,Constant.TO_LOGIN_ACTIVITY);
                }
                else
                {
                    showBottomDialogLoad();
                }
            }
        });


        my_comment_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    Intent intent =new Intent(getActivity(), MyCommentActivity.class);
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });

        my_publish_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    Intent intent =new Intent(getActivity(), MyPublishActivity.class);
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });

        myMessageLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    Intent intent =new Intent(getActivity(), OthersCommentActivity.class);
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });


        myConcernLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    Intent intent =new Intent(getActivity(), MyConcernActivity.class);
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });

        headImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                showBottomDialog();
            }
        });

        myHomePageLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    UserInfoShowActivity.activityStart(MyFragment.this.getActivity(),UserInfo.getInstance().UserId);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });

        myPrivateMessageLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UserInfo.getInstance().IsLogin)
                {
                    Intent intent=new Intent(MyFragment.this.getActivity(), FriendRequestActivity.class);
                    MyFragment.this.getActivity().startActivity(intent);
                }
                else
                {
                    Toast.makeText(getActivity(),"请登录",Toast.LENGTH_SHORT).show();
                }
            }
        });

        initViewModel();
        observeLiveData();
        return view;
    }

    private void initViewModel()
    {
        myViewModel=new ViewModelProvider(requireActivity(),new ViewModelProvider.AndroidViewModelFactory(getActivity().getApplication())).get(MyViewModel.class);
    }

    private void observeLiveData()
    {
        myViewModel.responseMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(s==null)
                    return;
                if(s.equals(Constant.HTTPS_GET_CALLBACK_SUCCESS))
                {
                    Message message=new Message();
                    message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                    message.arg1=CHANGE_HEAD_SUCCESSFUL;
                    MyHandler.sendMessage(message);
                }
                else
                {
                    Message message=new Message();
                    message.what=Constant.HTTPS_GET_CALLBACK_SUCCESS_MESSAGE;
                    message.arg1=CHANGE_HEAD_FAIL;
                    MyHandler.sendMessage(message);
                }
                myViewModel.responseMutableLiveData.setValue(null);
            }
        });
    }

    private void showBottomDialogLoad()
    {
        Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog_Load);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.button_dialog_load, null);
        TextView noLoadTextView=contentView.findViewById(R.id.bottom_dialog_no_load);

        noLoadTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserInfo.getInstance().headImage="";
                UserInfo.getInstance().IsLogin=false;
                UserInfo.getInstance().UserId=-1;
                bottomDialog.cancel();
                Intent intent =new Intent(getActivity(), LoginAndRegisterActivity.class);
                startActivityForResult(intent,Constant.TO_LOGIN_ACTIVITY);
            }
        });
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    //函数作用 显示底部对话框 以及配置好底部对话框的点击事件
    private void showBottomDialog()
    {
        Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.button_dialog, null);
        TextView takePicturesTextView=contentView.findViewById(R.id.bottom_dialog_take_pictures);
        TextView selectAlbumTextView=contentView.findViewById(R.id.bottom_dialog_from_album);

        takePicturesTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                outputImage= new File(getActivity().getExternalCacheDir(),String.valueOf(System.currentTimeMillis())+".jpg");
                if(outputImage.exists())
                    outputImage.delete();
                try {
                    outputImage.createNewFile();
                }
                catch (Exception e)
                {

                }
                imageUri= FileProvider.getUriForFile(getActivity(),"com.example.echoewish.fileprovider",outputImage);
                Intent cameraIntent=new Intent("android.media.action.IMAGE_CAPTURE");
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(cameraIntent, Constant.TO_CAMERA_ACTIVITY);
            }
        });


        selectAlbumTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent albumIntent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
                albumIntent.addCategory(Intent.CATEGORY_OPENABLE);
                albumIntent.setType("image/*");
                startActivityForResult(albumIntent, Constant.TO_ALBUM_ACTIVITY);
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case Constant.TO_CAMERA_ACTIVITY:
                if(resultCode== Activity.RESULT_OK)
                    try {
                        headImageView.setImageBitmap(BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri)));
                        myViewModel.updateHeadImage(outputImage);
                    }
                    catch (Exception e)
                    {

                    }

                break;
            case Constant.TO_ALBUM_ACTIVITY:
                if(resultCode== Activity.RESULT_OK&&data!=null)
                {
                    try {
                        Bitmap bitmap= BitmapFactory.decodeFileDescriptor(getActivity().getContentResolver().openFileDescriptor(data.getData(),"r").getFileDescriptor());
                        headImageView.setImageBitmap(bitmap);
                        outputImage= new File(getActivity().getExternalCacheDir(),String.valueOf(System.currentTimeMillis())+".jpg");
                        if(outputImage.exists())
                            outputImage.delete();
                        try {
                            outputImage.createNewFile();
                        }
                        catch (Exception e)
                        {

                        }
                        try {
                            outputImage.createNewFile();
                            FileOutputStream fileOutputStream = new FileOutputStream(outputImage);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        myViewModel.updateHeadImage(outputImage);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }
                break;
            case Constant.TO_LOGIN_ACTIVITY:
                    if(UserInfo.getInstance().IsLogin)
                    {
                        nameTextView.setText(UserInfo.getInstance().name);
                        if(UserInfo.getInstance().headImage!=null&&!UserInfo.getInstance().headImage.equals(""))
                        {
                            Glide.with(getActivity()).load(Constant.HEAD_IMAGE_URL+UserInfo.getInstance().headImage).into(headImageView);
                        }
                        else
                            Glide.with(getActivity()).load(R.drawable.no_load).into(headImageView);
                    }
                    else
                    {
                        nameTextView.setText("未登录");
                        Glide.with(getActivity()).load(R.drawable.no_load).into(headImageView);
                    }
                break;

        }
    }
}